// 页面路径：store/index.js 
import Vue from 'vue'
import Vuex from 'vuex'
import $H from '@/static/common/request.js';

Vue.use(Vuex);//vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
	state:{//存放状态
		"user":null,
		"token":null
	},
	actions:{
		authMethod({ state },callback){
			if(!state.token){
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				return uni.navigateTo({
					url:'/pages/login/login'
				});
			}
			callback()
		},
		// 初始化用户登录状态
		initUser({ state }){
			let u = uni.getStorageSync('user')
			let t = uni.getStorageSync('token')
			if(u){
				state.user = JSON.parse(u)
				state.token = t
			}
		},
		logout({ state }){
			$H.post('/logout',{},{
				token:true,toast:false
			})
			state.user = null
			state.token = null
			uni.removeStorageSync('user')
			uni.removeStorageSync('token')
		},
		login({ state },user){
			state.user = user
			state.token = user.token
			
			uni.setStorageSync('user',JSON.stringify(user))
			uni.setStorageSync('token',user.token)
		},
		getUserInfo({ state }){
			if(!state.user){
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateTo({
						url: ('/pages/login/login')
					})
				}, 2000);
			}
			$H.get('/user/info',{
				token:true,
				noJump:true,
				toast:false
			}).then(res=>{
				state.user = res.data
				uni.setStorage({
					key:"user",
					data:JSON.stringify(state.user)
				})
			})
		}
	}
})
export default store